<template>
  <div class="user-moments-container">
    <!-- 返回按钮 -->
    <div class="back-button" @click="goBack">
      <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
        <path d="M15 18L9 12L15 6" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>
    </div>
    
    <!-- 顶部背景和用户信息 -->
    <div class="user-header">
      <div class="header-bg">
        <img src="https://images.unsplash.com/photo-1519608487953-e999c86e7455?w=400&h=300&fit=crop" alt="背景" />
      </div>
      <div class="user-profile">
        <div class="profile-info">
          <div class="profile-top">
            <h2 class="profile-name">{{currentUserName}}</h2>
            <img :src="currentAvatar" alt="头像" class="profile-avatar" />
          </div>
          <p class="profile-motto">{{currentSign}}</p>
        </div>
      </div>
    </div>

    <!-- 时间轴朋友圈列表 -->
    <div class="timeline-list">
      <div v-for="moment in moments" :key="moment.id" class="timeline-item" @click="goToDetail(moment.id)">
        <!-- 日期 -->
        <div class="timeline-date">
          <span class="date-day">{{ moment.dateDay }}</span>
          <span class="date-month">{{ moment.dateMonth }}</span>
        </div>
        
        <!-- 内容区域 -->
        <div class="timeline-content">
          <!-- 纯文字内容 -->
          <div v-if="isTextOnly(moment)" class="text-only-content">
            <span class="text-only">{{ moment.text }}</span>
          </div>
          
          <!-- 有媒体的内容 -->
          <div v-else class="media-content">
            <!-- 文字区域 -->
            <div class="media-text-section">
              <!-- 文字内容 -->
              <div v-if="moment.text" class="moment-text">{{ moment.text }}</div>
              
              <!-- 位置 -->
              <div v-if="moment.location" class="location-info">
                <i class="location-icon">📍</i>
                <span>{{ moment.location }}</span>
              </div>
            </div>
            
            <!-- 媒体区域 -->
            <div class="media-media-section">
              <!-- 图片 -->
              <div v-if="moment.images && moment.images.length > 0" class="images-grid" :class="getImageGridClass(moment.images.length)">
                <el-image 
                  v-for="(image, index) in moment.images" 
                  :key="index" 
                  :src="image" 
                  class="image-item"
                  fit="cover"
                  :alt="`图片${index + 1}`"
                  @click="previewImages(moment.images, index)"
                />
              </div>

              <!-- 视频 -->
              <div v-if="moment.video" class="video-content">
                <video :src="moment.video" controls :poster="moment.videoPoster"></video>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图片预览 -->
    <el-image-viewer 
      v-if="imagePreview.visible"
      :url-list="imagePreview.urlList"
      :initial-index="imagePreview.initialIndex"
      @close="closeImagePreview"
      teleported
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter,useRoute } from 'vue-router'
import api from '@/utils/http'
import { ElMessage } from 'element-plus'

interface User {
  id: number
  name: string
  avatar: string
}

interface Comment {
  id: number
  user: User
  text: string
  replyTo?: string
}

interface Moment {
  id: number
  user: User
  text?: string
  images?: string[]
  video?: string
  videoPoster?: string
  location?: string
  time: string
  dateDay: string
  dateMonth: string
  likes: User[]
  comments: Comment[]
  isLiked: boolean
  showCommentInput: boolean
  newComment: string
  type?: number
  fileUrl?: string
}

// 数据状态
const moments = ref<Moment[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)

const lookUserId = ref()
const currentUserId = ref()
const currentUserName = ref()
const currentAvatar = ref()
const currentSign = ref()

// 路由
const router = useRouter()
const route = useRoute()

// 返回上一页
const goBack = () => {
  router.back()
}

// 判断是否为纯文字内容
const isTextOnly = (moment: Moment): boolean => {
  return !!(moment.text && !moment.images?.length && !moment.video)
}

// 跳转到详情页面
const goToDetail = (momentId: number) => {
  router.push(`/momentDetail?id=${momentId}`)
}

// 图片预览相关
const imagePreview = reactive({
  visible: false,
  urlList: [] as string[],
  initialIndex: 0
})

// 预览图片
const previewImages = (images: string[], index: number) => {
  imagePreview.urlList = images
  imagePreview.initialIndex = index
  imagePreview.visible = true
}

// 关闭图片预览
const closeImagePreview = () => {
  imagePreview.visible = false
}

// 获取图片网格样式类
const getImageGridClass = (count: number): string => {
  if (count === 1) return 'grid-single'
  if (count === 2) return 'grid-double'
  if (count === 3) return 'grid-three-waterfall'
  if (count === 4) return 'grid-four'
  if (count === 5) return 'grid-five-waterfall'
  if (count === 6) return 'grid-full-width'
  if (count === 7) return 'grid-seven-waterfall'
  if (count > 7) return 'grid-full-width'
  return 'grid-multiple'
}

// 格式化时间
const formatTime = (dateTime: string) => {
  if (!dateTime) return { time: '', dateDay: '', dateMonth: '' }
  const date = new Date(dateTime)
  
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  
const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', 
                   '7月', '8月', '9月', '10月', '11月', '12月'];
  
  return {
    time: `${year}年${month}月${day}日`,
    dateDay: day.toString().padStart(2, '0'),
    dateMonth: monthNames[date.getMonth()]
  }
}

// 转换后端数据为前端格式
const transformMomentData = (backendData: any): Moment => {
  const timeInfo = formatTime(backendData.createTime)
  
  const moment: Moment = {
    id: backendData.id,
    user: {
      id: backendData.userId,
      name: backendData.username,
      avatar: backendData.avatar
    },
    text: backendData.title,
    time: timeInfo.time,
    dateDay: timeInfo.dateDay,
    dateMonth: timeInfo.dateMonth,
    likes: backendData.likeUserList?.map((like: any) => ({
      id: like.userId,
      name: like.username,
      avatar: like.avatar
    })) || [],
    comments: backendData.commentList?.map((comment: any) => ({
      id: comment.id,
      user: {
        id: comment.userId,
        name: comment.username,
        avatar: comment.avatar
      },
      text: comment.content,
      replyTo: comment.pusername
    })) || [],
    isLiked: backendData.isLike === 1,
    showCommentInput: false,
    newComment: '',
    type: backendData.type,
    fileUrl: backendData.fileUrl,
    location: backendData.address
  }

  // 处理文件URL
  if (backendData.type === 1 && backendData.fileUrl) {
    // 图片类型
    moment.images = backendData.fileUrl.split(',').filter((url: string) => url.trim())
  } else if (backendData.type === 2 && backendData.fileUrl) {
    // 视频类型
    moment.video = backendData.fileUrl
  }

  return moment
}

// 获取用户朋友圈列表
const loadUserMoments = async (page: number = 1, isLoadMore: boolean = false) => {
  if (loading.value) return
  
  loading.value = true
  try {
    const response = await api.get(`/moments/moment/userMoments/${lookUserId.value}/${currentUserId.value}`, {
      params: {
        pageNo: page,
        pageSize: pageSize.value
      }
    })
    
    if (response.data && response.data.code === 200) {
      currentUserName.value = response.data.data.username
      currentAvatar.value = response.data.data.avatar
      currentSign.value = response.data.data.signature
      const pageData = response.data.data.momentItemList
      const newMoments = pageData.records.map(transformMomentData)
      
      if (isLoadMore) {
        moments.value.push(...newMoments)
      } else {
        moments.value = newMoments
      }
      
      hasMore.value = pageData.current < pageData.pages
      currentPage.value = pageData.current
    }
  } catch (error) {
    console.error('加载用户朋友圈失败:', error)
  } finally {
    loading.value = false
  }
}

const getUserIdFromToken = (token: string) => {
  if (!token) return '';
  try {
    const payloadBase64 = token.split('.')[1];
    const decoded = JSON.parse(atob(payloadBase64));
    return decoded.sub; 
  } catch (error) {
    console.error('Token解析失败:', error);
    return '';
  }
};

// 组件挂载时加载数据
onMounted(() => {
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.warning('未检测到登录态，请先登录');
    return;
  }
  currentUserId.value = getUserIdFromToken(token);
  lookUserId.value = route.query.userId
  loadUserMoments()
})

</script>

<style scoped>
.user-moments-container {
  min-height: 100vh;
  background: #f5f5f5;
  position: relative;
}

/* 返回按钮 */
.back-button {
  position: fixed;
  top: 20px;
  left: 20px;
  width: 44px;
  height: 44px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 100;
  transition: background-color 0.2s;
}

.back-button:hover {
  background: rgba(0, 0, 0, 0.5);
}

.back-button svg {
  pointer-events: none;
}

/* 用户头部区域 */
.user-header {
  position: relative;
  height: 300px;
  overflow: visible;
  z-index: 20;
}

.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.header-bg img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-profile {
  position: absolute;
  bottom: -30px;
  right: 20px;
  color: white;
  z-index: 25;
}

.profile-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.profile-top {
  display: flex;
  align-items: center;
  gap: 15px;
}

.profile-name {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: white;
  text-align: right;
}

.profile-avatar {
  width: 70px;
  height: 70px;
  border-radius: 8px;
  border: 3px solid white;
  flex-shrink: 0;
}

.profile-motto {
  font-size: 14px;
  margin: 0;
  color: gray;
  line-height: 1.3;
  text-align: right;
  margin-right: 0;
}

/* 时间轴列表 */
.timeline-list {
  padding: 70px 20px 20px 20px;
  background: white;
  margin-top: -50px;
  position: relative;
  z-index: 5;
}

.timeline-item {
  display: flex;
  margin-bottom: 30px;
  cursor: pointer;
  transition: opacity 0.2s;
}

.timeline-item:hover {
  opacity: 0.8;
}

.timeline-item:last-child {
  margin-bottom: 0;
}

/* 时间轴日期 */
.timeline-date {
  width: 80px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  margin-right: 20px;
}

.date-day {
  font-size: 32px;
  font-weight: 600;
  color: #333;
  line-height: 1;
}

.date-month {
  font-size: 14px;
  color: #999;
  margin-top: 2px;
  text-transform: uppercase;
}

/* 时间轴内容 */
.timeline-content {
  flex: 1;
  min-width: 0;
}

/* 纯文字内容 */
.text-only-content {
  background: #f0f0f0;
  padding: 12px 16px;
  border-radius: 10px;
  max-width: 300px;
}

.text-only {
  font-size: 16px;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 有媒体的内容 */
.media-content {
  display: flex;
  flex-direction: row;
  gap: 15px;
  max-width: 100%;
  align-items: flex-start;
  min-height: 100px;
}

.media-media-section {
  width: 120px;
  height: 120px;
  flex-shrink: 0;
  order: 1;
}

.media-text-section {
  flex: 1;
  min-width: 0;
  order: 2;
}

.moment-text {
  font-size: 16px;
  line-height: 1.4;
  color: #333;
  margin: 0;
  white-space: pre-wrap;
  min-height: 120px;
}

/* 图片网格 */
.images-grid {
  display: grid;
  gap: 2px;
  margin-bottom: 8px;
  width: 120px;
  height: 120px;
}

.grid-single {
  grid-template-columns: 1fr;
}

.grid-double {
  grid-template-columns: 1fr 1fr;
}

.grid-three-waterfall {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  grid-template-areas: 
    "img1 img2"
    "img3 img3";
}

.grid-three-waterfall .image-item:nth-child(1) {
  grid-area: img1;
}

.grid-three-waterfall .image-item:nth-child(2) {
  grid-area: img2;
}

.grid-three-waterfall .image-item:nth-child(3) {
  grid-area: img3;
  aspect-ratio: 2/1; /* 让底部图片更宽一些 */
}

.grid-four {
  grid-template-columns: 1fr 1fr;
}

.grid-five-waterfall {
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  grid-template-areas: 
    "img1 img1 img2"
    "img3 img4 img5";
}

.grid-five-waterfall .image-item:nth-child(1) {
  grid-area: img1;
  aspect-ratio: 2/1;
}

.grid-five-waterfall .image-item:nth-child(2) {
  grid-area: img2;
}

.grid-five-waterfall .image-item:nth-child(3) {
  grid-area: img3;
}

.grid-five-waterfall .image-item:nth-child(4) {
  grid-area: img4;
}

.grid-five-waterfall .image-item:nth-child(5) {
  grid-area: img5;
}

.grid-seven-waterfall {
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-areas: 
    "img1 img1 img2"
    "img3 img3 img4"
    "img5 img6 img7";
}

.grid-seven-waterfall .image-item:nth-child(1) {
  grid-area: img1;
  aspect-ratio: 2/1;
}

.grid-seven-waterfall .image-item:nth-child(2) {
  grid-area: img2;
}

.grid-seven-waterfall .image-item:nth-child(3) {
  grid-area: img3;
  aspect-ratio: 2/1;
}

.grid-seven-waterfall .image-item:nth-child(4) {
  grid-area: img4;
}

.grid-seven-waterfall .image-item:nth-child(5) {
  grid-area: img5;
}

.grid-seven-waterfall .image-item:nth-child(6) {
  grid-area: img6;
}

.grid-seven-waterfall .image-item:nth-child(7) {
  grid-area: img7;
}

.grid-multiple {
  grid-template-columns: repeat(3, 1fr);
}

.grid-full-width {
  grid-template-columns: repeat(3, 1fr);
}

.image-item {
  aspect-ratio: 1;
  overflow: hidden;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.2s, opacity 0.2s;
  width: 100%;
  height: 100%;
}

.image-item:hover {
  transform: scale(0.98);
  opacity: 0.9;
}

.image-item :deep(.el-image) {
  width: 100%;
  height: 100%;
}

.image-item :deep(.el-image img) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 视频 */
.video-content {
  width: 120px;
  height: 120px;
  margin-bottom: 8px;
}

.video-content video {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  object-fit: cover;
}

/* 位置信息 */
.location-info {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #576b95;
  margin-top: 8px;
}

.location-icon {
  margin-right: 4px;
  font-style: normal;
}



/* 移动端适配 */
@media (max-width: 768px) {
  .back-button {
    top: 15px;
    left: 15px;
    width: 40px;
    height: 40px;
  }
  
  .back-button svg {
    width: 20px;
    height: 20px;
  }
  
  .user-header {
    height: 250px;
  }
  
  .user-profile {
    bottom: -30px;
    right: 15px;
  }
  
  .profile-info {
    gap: 6px;
  }
  
  .profile-top {
    gap: 12px;
  }
  
  .profile-avatar {
    width: 60px;
    height: 60px;
  }
  
  .profile-name {
    font-size: 20px;
  }
  
  .profile-motto {
    font-size: 13px;
  }
  
  .timeline-list {
    padding: 100px 15px 15px 15px;
    margin-top: -40px;
  }
  
  .timeline-item {
    margin-bottom: 25px;
  }
  
  .timeline-date {
    width: 50px;
    margin-right: 12px;
  }
  
  .date-day {
    font-size: 24px;
  }
  
  .date-month {
    font-size: 11px;
  }
  
  .text-only-content {
    max-width: 300px;
    padding: 8px;
  }
  
  .text-only {
    font-size: 15px;
  }
  
  .media-content {
    flex-direction: row;
    gap: 10px;
  }
  
  .media-media-section {
    width: 120px;
    height: 120px;
    flex-shrink: 0;
    order: 1;
  }
  
  .media-text-section {
    flex: 1;
    min-width: 0;
    order: 2;
  }
  
  .images-grid {
    width: 120px;
    height: 120px;
  }
  
  .grid-three-waterfall {
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;
    grid-template-areas: 
      "img1 img2"
      "img3 img3";
  }

  .grid-three-waterfall .image-item:nth-child(1) {
    grid-area: img1;
  }

  .grid-three-waterfall .image-item:nth-child(2) {
    grid-area: img2;
  }

  .grid-three-waterfall .image-item:nth-child(3) {
    grid-area: img3;
    aspect-ratio: 2/1; /* 让底部图片更宽一些 */
  }
  
  .grid-five-waterfall {
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr;
    grid-template-areas: 
      "img1 img1 img2"
      "img3 img4 img5";
  }

  .grid-five-waterfall .image-item:nth-child(1) {
    grid-area: img1;
    aspect-ratio: 2/1;
  }

  .grid-five-waterfall .image-item:nth-child(2) {
    grid-area: img2;
  }

  .grid-five-waterfall .image-item:nth-child(3) {
    grid-area: img3;
  }

  .grid-five-waterfall .image-item:nth-child(4) {
    grid-area: img4;
  }

  .grid-five-waterfall .image-item:nth-child(5) {
    grid-area: img5;
  }

  .grid-seven-waterfall {
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr;
    grid-template-areas: 
      "img1 img1 img2"
      "img3 img3 img4"
      "img5 img6 img7";
  }

  .grid-seven-waterfall .image-item:nth-child(1) {
    grid-area: img1;
    aspect-ratio: 2/1;
  }

  .grid-seven-waterfall .image-item:nth-child(2) {
    grid-area: img2;
  }

  .grid-seven-waterfall .image-item:nth-child(3) {
    grid-area: img3;
    aspect-ratio: 2/1;
  }

  .grid-seven-waterfall .image-item:nth-child(4) {
    grid-area: img4;
  }

  .grid-seven-waterfall .image-item:nth-child(5) {
    grid-area: img5;
  }

  .grid-seven-waterfall .image-item:nth-child(6) {
    grid-area: img6;
  }

  .grid-seven-waterfall .image-item:nth-child(7) {
    grid-area: img7;
  }
  
  .video-content {
    width: 120px;
    height: 120px;
  }
  
  .video-content video {
    width: 120px;
    height: 120px;
  }
  
  .moment-text {
    font-size: 15px;
    min-height: 80px;
  }
}
</style>
